#include <stdlib.h>
#include <vector>
#include "jnilib_jnimethods.h"
#include "kuwahara.h"

//#define LOG_TAG "Harris"
//#define LOGV(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)

using namespace std;

/* int[] support */
int SWIG_JavaArrayInInt(JNIEnv *jenv, jint **jarr, int **carr, jintArray input) {

	int i;
	jsize sz;
	if (!input) {
		//    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "null array");
		return 0;
	}
	sz = jenv->GetArrayLength(input);
	*jarr = jenv->GetIntArrayElements(input, 0);
	if (!*jarr)
		return 0;
	*carr = new int[sz];
	if (!*carr) {
		//    SWIG_JavaThrowException(jenv, SWIG_JavaOutOfMemoryError, "array memory allocation failed");
		return 0;
	}
	for (i = 0; i < sz; i++)
		(*carr)[i] = (int) (*jarr)[i];
	return 1;
}


JNIEXPORT jintArray JNICALL Java_jnilib_jnimethods_kuwahara(JNIEnv *jenv, jclass jcls,
		jintArray jpixels, jint jwidth, jint jheight, jint jn) {

	int *pixels = (int *) 0;
	jint *jarr1;
	if (!SWIG_JavaArrayInInt(jenv, &jarr1, &pixels, jpixels))
		return 0;


	int width = (int) jwidth;
	int height = (int) jheight;
	int n = (int) jn;


	vector<int> finalpixels(width * height);
	finalpixels = kuwahara(pixels, width, height, n);

	//Convert vector<int> to jintArray
	jintArray jfinalpixels = jenv->NewIntArray(finalpixels.size());
	jenv->SetIntArrayRegion(jfinalpixels, 0, finalpixels.size(),
			(jint *) &finalpixels[0]);


	jenv->ReleaseIntArrayElements(jpixels, jarr1, 0);		// this is the leak point.
	delete[] pixels;     									// this is the leak point.
	finalpixels.clear();

	return jfinalpixels;
}
